/*
 * Created by Jaren at 2023/9/25 9:28
 */
import 'dart:typed_data';

import 'package:binary/binary.dart';
import 'package:inmotion_protocol/base/base_message.dart';
import 'package:inmotion_protocol/elephant/constant.dart';
import 'package:inmotion_protocol/util/byte_util.dart';

class ElephantMessage extends IMessage {
  final Uint8ClampedList head = ElephantConstant.msgHeadBytes; // 消息头，2byte
  late Uint8 length; // 消息长度，从function开始计算
  late Uint8 encrypt; // 加密位
  late Uint8 device; // 设备号
  late Uint8 function; // 功能码
  late Uint8 extra; // 扩展功能码
  late Uint8ClampedList data; // 数据
  late Uint8ClampedList check; // 校验位，2byte

  ElephantMessage();

  ElephantMessage.create(this.length, this.encrypt, this.device, this.function, this.extra, this.data, this.check);

  @override
  String genMsgIdentity() {
    if (_isFwUpdateMsg(this) || _isReadLogMsg(this)) return "${function.value}|".hashCode.toString();
    return "${function.value}|${extra.value}".hashCode.toString();
  }

  int totalLength() {
    return ElephantConstant.msgHeadBytesLength + 1 + 1 + 1 + 1 + 1 + data.length + ElephantConstant.msgCheckBytesLength;
  }

  @override
  String toString() {
    return 'ElephantMessage{'
        'head: ${ByteUtil.bytes2HexString(head)}, '
        'length: ${length.value}, '
        'encrypt: 0x${ByteUtil.byte2Hex(encrypt.value)}, '
        'device: 0x${ByteUtil.byte2Hex(device.value)}, '
        'function: 0x${ByteUtil.byte2Hex(function.value)}, '
        'extra: 0x${ByteUtil.byte2Hex(extra.value)}, '
        'data: ${ByteUtil.bytes2HexString(data)}, '
        'check: ${ByteUtil.bytes2HexString(check)}'
        '}';
  }

  static bool _isFwUpdateMsg(ElephantMessage msg) {
    return msg.function.value == ElephantConstant.funcFwUpdatePrepare ||
        msg.function.value == ElephantConstant.funcFwUpdateFileTransfer ||
        msg.function.value == ElephantConstant.funcFwUpdateFileCheck ||
        msg.function.value == ElephantConstant.funcFwUpdateReboot;
  }

  static bool _isReadLogMsg(ElephantMessage msg) {
    return msg.function.value == ElephantConstant.funcLog;
  }
}
